package com.njcb.ams.factory.comm;

import com.njcb.ams.util.AmsAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Collection;

/**
 * 系统缓存工具
 * @author LOONG
 */
@Component
public class AmsCacheUtils {
    private static final String CACHE_NAME_DEFAULT = "UserTempParamCache";
    @Autowired
    private CacheManager cacheManager;

    private static CacheManager cm;

    @PostConstruct
    public void init() {
        cm = cacheManager;
    }

    /**
     * 缓存
     * @param cacheName 缓存管理器名称
     * @param key       缓存key
     * @param value     缓存value
     */
    public static void put(String cacheName, String key, Object value) {
        Cache cache = getCache(cacheName);
        cache.put(key, value);
    }

    /**
     * @param cacheName 缓存管理器名称
     * @param key       缓存key
     * @return 缓存对象
     */
    public static Object get(String cacheName, String key) {
        Cache cache = getCache(cacheName);
        if (cache == null) {
            return null;
        }
        return cache.get(key).get();
    }

    /**
     * @param cacheName 缓存管理器名称
     * @param key       缓存key
     * @param clazz     返回Class
     * @param <T>       返回对象泛型
     * @return 缓存对象
     */
    public static <T> T get(String cacheName, String key, Class<T> clazz) {
        Cache cache = getCache(cacheName);
        return cache.get(key, clazz);
    }

    /**
     * @param cacheName 缓存管理器名称
     * @param key       缓存key
     */
    public static void evict(String cacheName, String key) {
        Cache cache = getCache(cacheName);
        cache.evict(key);
    }

    /**
     * @param key   缓存key
     * @param value 缓存value
     */
    public static void put(String key, Object value) {
        put(CACHE_NAME_DEFAULT, key, value);
    }

    /**
     * @param key 缓存key
     * @return 缓存对象
     */
    public static Object get(String key) {
        return get(CACHE_NAME_DEFAULT, key);
    }

    /**
     * @param key 缓存key
     */
    public static void evict(String key) {
        Cache cache = getCache(CACHE_NAME_DEFAULT);
        cache.evict(key);
    }

    private static Cache getCache(String cacheName){
        Cache cache = cm.getCache(cacheName);
        Collection<String> aa =  cm.getCacheNames();
        AmsAssert.notNull(cache,"缓存管理器["+cacheName+"]不存在");
        return cache;
    }

}
